﻿using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;


namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 用户管理相关
    /// </summary>
    /// =======================================================================
    /// 类名：ManagerController ManagerController的备注：ManagerController~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/8/16        陈峰             新建<br/>
    /// =======================================================================<br/>
    public partial class ManagerController
    {

        #region 用户管理

        #region 视图
        public ActionResult UserManager()
        {
            ViewBag.eid = LogOnUser.EnterpriseId;
            ViewBag.uid = LogOnUser.UserID;
   
            return View();
        }

 
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditUser(int? id)
        {
            Sys_User result = _mservice.GetUserInfoById((int)id);
            ViewBag.User = result;
            ViewBag.EName = LogOnUser.EnterpriseName;
            return View();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>


        public JsonResult CheckUserName(string LoginName)
        {
            var result = _mservice.GetByUserName(LoginName);
            return Json(new { valid = result });

        }

        public ActionResult AddUser()
        {
                   
            List<V_Role> result = _mservice.GetRoleAllService(LogOnUser.EnterpriseId,LogOnUser.RoleID);
            List<SelectListItem> items = new List<SelectListItem>();
            SelectListItem it = new SelectListItem() { Text = "无", Value = "0" };
            items.Add(it);
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].RoleName, Value = result[i].ID.ToString() };
                items.Add(item);
            }
            ViewData["Rid"] = items;
            ViewBag.EnterpriseId = LogOnUser.EnterpriseId;
            ViewBag.EName = LogOnUser.EnterpriseName;
            return View();
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public ActionResult ResetCode()
        {
            return View();
        }


        #endregion

        #region 增
        /// <summary>
        /// 添加用户
        /// </summary> n  
        /// <param name="_user">用户的表单提交</param>
        /// <returns>影响的行数</returns>
        public int AddUserInfo(Sys_User _user, int rid)
        {
            _user.UserImg = "/Content/HomePage/home/head_portrait.png";
            _user.ViewDel = 0;
            _user.ViewFlag = 1;
            _user.EnterpriseId = LogOnUser.EnterpriseId;
            _user.ChangeDate = DateTime.Now;
            _user.ChangeLoginID = LogOnUser.UserID;
            _user.ChangeLoginName = LogOnUser.LoginName;
            _user.Type = 1;
            _user.Distributor = 0;
            _user.Pwd = MD5Manager.Gen_MD5(_user.Pwd, true);
            _user.LoginName = _user.LoginName.Replace(" ", "").Trim();
            int uid = _mservice.AddUserInfoService(_user);
            Sys_RoleUserInfo ru = new Sys_RoleUserInfo();
            ru.Rid = rid;
            ru.Uid = uid;
            var userId = _mservice.AddRoleUserInfoService(ru);
            //当创建的角色为试用角色时，创建试用机构，并将该用户机构改为试用机构
            if (rid == 15)
            {
                int EID = AddTryoutEnterprise(uid);
                var result = _mservice.updateUserEID(EID, uid);
            }
            return userId;
        }

        /// <summary>
        /// 为试用账号添加试用机构
        /// </summary>
        /// <param name="userId">试用账号Id</param>
        /// <returns></returns>
        public int AddTryoutEnterprise(int userId)
        {
           Organization_Enterprise model = new Organization_Enterprise();

            model.CreateDate = DateTime.Now;
            model.ChangeLoginID = base.LogOnUser.UserID;
            model.ChangeLoginName = base.LogOnUser.LoginName;
            model.ChangeDate = DateTime.Now;
            model.Code = "0000";
            model.StartTime = DateTime.Now;
            model.ViewDel = 0;
            model.ViewFlag = 1;
            //model.Img = filePath;
            model.SuperiorsOrganization = LogOnUser.EnterpriseId;
 
            model.EnterpriseName = "试用机构";
            model.OrganizationForm = 2;

            int Eid = _mservice.AddEnterpriseService(model);

            model.Code = Eid.ToString().PadLeft(5, '0');
            model.ID = Convert.ToInt32(Eid.ToString().PadRight(5, '0'));

            var result = _mservice.updateEnterpriseIdToTryOut(Eid);
            //_mservice.updEnterpriseService(model);

            return model.ID;

        }








        #endregion

        #region 改
        /// <summary>
        /// 改  编辑用户信息
        /// </summary>
        /// <param name="_user"></param>
        /// <returns></returns>
        public int EditUserInfo(Sys_User _user)
        {
            _user.Remark=_user.Remark?? " ";
            _user.ChangeDate = DateTime.Now;
            _user.ChangeLoginID = LogOnUser.UserID;
            _user.ChangeLoginName = LogOnUser.LoginName;
            int result = _mservice.EditUserInfoService(_user);
            return result;
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="RoleId">角色ID字符串,逗号分隔</param>
        /// <returns></returns>
        public int EditUserRole(int id, string RoleId)
        {
            if (RoleId=="")
            {
                return 0;
            }
            RoleId = RoleId.TrimEnd(',');
            string[] c = RoleId.Split(',');

            int result = _mservice.EditUserRoleService(id, c);
            return result;
        }


        #endregion

        #region 删

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">修改用户ID</param>
        /// <returns>1||0</returns>
        public int DelUser(int id)
        {
            Sys_User user = new Sys_User();
            user.ID = id;
            user.ViewDel = 1;
            return _mservice.DelUserService(user);
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public int ResetUserPWD(int id, string newPwd)
        {
            Sys_User user = _mservice.GetUserInfoById(id);
            /*使用MD5替换DES*/
            user.Pwd = MD5Manager.Gen_MD5(newPwd, true);
            //user.Pwd = EDS3.DESEnCode(newPwd);
            user.ChangeLoginID = LogOnUser.UserID;
            user.ChangeLoginName = LogOnUser.LoginName;
            return _mservice.EditUserInfoService(user);

        }

        #endregion

        #region 导出EXCEL
        public ActionResult Execls(string key)
        {
         
                var model = _mservice.GetAllUser(key,LogOnUser.EnterpriseId);
            
           
            var _byte_catch = Excel.Exprot<Sys_User>(model.ToList(), new string[] { "真实姓名", "登录名", "用户状态", "手机号", "备注", "所属机构", "角色名称" }, q =>
            {
                return new object[] { 
		q.RealName,
		q.LoginName,
		q.ViewFlag,
		q.Modile,
		q.Remark,
		q.EnterpriseName,
	    q.LandlinePhone,
		q.roleNames,
				};
            }, "User");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion

        #region 查
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetUserInfo(int pageIndex, int pageSize, string SeachWhere,int Eid)
        {
            var userid = LogOnUser.UserID;
            var enterpriseId = LogOnUser.EnterpriseId;
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;

            string whereStr = Eid != 0 
                ? "  u.ViewDel=0  AND  u.ID  not in(" + userid + ")  and u.EnterpriseId=" + Eid + " "
                : "u.ViewDel=0  AND  u.ID  not in(" + userid + ") ";
        

            if (LogOnUser.Distributor != 0)//经销商
            {
              //  whereStr += "    and u.ChangeLoginID=" + LogOnUser.UserID;
                whereStr += string.Format(" and  FIND_IN_SET(u.distributor,getDiscChild({0})) ", LogOnUser.Distributor);
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    whereStr += LogOnUser.JuniorEnterprise != null ? "    and  u.EnterpriseId in (" + _mservice.GetSonEnterpriseStrArray(LogOnUser.EnterpriseId) + ") " : "   EnterpriseId=" + LogOnUser.EnterpriseId + "   ";
                }

            }
            pm.StrCondition = SeachWhere != "" && SeachWhere!=null ? " ( u.RealName like '%" + SeachWhere + "%' or u.LoginName like '%" + SeachWhere + "%' ) " : whereStr;
            var model = _mservice.GetUserInfoService(ref pm, whereStr);
            Hashtable ht = new Hashtable();
            ht.Add("data",model);
            ht.Add("eName",LogOnUser.EnterpriseName);
            return Json(ht);
        }

        #endregion

        #endregion


        public JsonResult GetRoleUserInfo(int? id)
        {
            List<Sys_RoleUserInfo> RoleUserInfo = _mservice.GetRoleUserInfoByUserId((int)id).ToList();
            return Json(RoleUserInfo);
        }

        /// <summary>
        /// 获取当前机构所有用户
        /// </summary>
        /// <param name="EID"></param>
        /// <returns></returns>
        public ActionResult GetSysUserListByEID()
        {
            var EID = LogOnUser.EnterpriseId;
            var result = _mservice.GetSysUserListByEID(EID);
            return Json(result);
        }


        public ActionResult GetNodeAddUserList()
        {
            var EID = LogOnUser.EnterpriseId;
            var result = _mservice.GetNodeAddUserListByEID(EID);
            return Json(result);
        }
 

        #region 仓库管理 

        public ActionResult WareHouse()
        {
            return View();
        }

        //增加或编辑管理
        //Pass 1
        public ActionResult AEditWare()
        {
            ViewData["EnterpriseId"] = EnterpriseDropdownList(0);
            ViewData["SaleAreaId"] = new FleeGoodsController().SelSaleAreaList(0);
            return View();
        }

        //Pass 1
        public ActionResult EditWare(int id)
        {
            AntiFleeing_Warehouse a = _mservice.GeWarehouseModelId(id);
            if (a.EnterpriseId.HasValue)
            {
                ViewData["EnterpriseId"] = EnterpriseDropdownList(a.EnterpriseId.Value); 
            }
            ViewBag.WareHouse = a;
            return View();
        }
        /// <summary>
        /// 下拉框绑定
        /// </summary>
        /// <param name="EnterpriseId"></param>
        /// <returns></returns>

        public JsonResult GetArealist(int Eid)
        {
            return Json(_mservice.GetArealistService(Eid), JsonRequestBehavior.AllowGet);
        }
        //仓库编辑时绑定下拉框
        //Pass 1
        public JsonResult GetEditArealist(int Id)
        {
            var saleAreaList = new List<SelectListItem>();
            if (Id == 0) saleAreaList.Add(new SelectListItem() { Text = "--请选择--", Value = "0", Selected = true });
            saleAreaList.AddRange(new FleeGoodsController().SelSaleAreaList(Id));
            return Json(saleAreaList, JsonRequestBehavior.AllowGet);
        }

        //Pass 1
        public List<SelectListItem> EnterpriseDropdownList(int EnterpriseId)
        {
            List<Organization_Enterprise> result = _mservice.GetAntiService(LogOnUser.EnterpriseId);
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem() { Text = "--请选择--", Value = "" });
            items.AddRange(result.Select(p =>
            {
                return new SelectListItem
                {
                    Text = p.EnterpriseName,
                    Value = p.ID.ToString(),
                    Selected = EnterpriseId == p.ID
                };
            }));
            return items;
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="Wsearch"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult GetWareHouseList(string Wsearch, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            if (LogOnUser.Distributor != 0)//经销商
            {
                pm.StrCondition = " and ChangeLoginID=" + LogOnUser.UserID;
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise)) { pm.StrCondition = " and EnterpriseId  in (0)"; }
                    else
                    {
                        pm.StrCondition = " and EnterpriseId in (" + LogOnUser.JuniorEnterprise + ")";
                    }
                }
                else
                {
                    pm.StrCondition = " and 1=1";
                }
            }
            string strWhere = Wsearch != null ? " and  WarehouseName like '%" + Wsearch + "%' " : Wsearch;
            pm.StrCondition += strWhere;
            var model = _mservice.GetWareHouseService(ref pm, Wsearch);
            return Json(model);
        }

        /// <summary>
        /// 新增仓库
        /// NotPass 1
        /// </summary>
        public int AddWareHouse(AntiFleeing_Warehouse Warehouse)
        {
            L.EntityModel.AntiFleeing_Warehouse wh = new L.EntityModel.AntiFleeing_Warehouse();
            wh.EnterpriseId = LogOnUser.EnterpriseId;
            wh.WarehouseName = Warehouse.WarehouseName;
            wh.Address = Warehouse.Address;
            wh.Contacts = Warehouse.Contacts;
            wh.ContactTel = Warehouse.ContactTel;
            wh.Remark = Warehouse.Remark;
            wh.ViewDel = 0;
            wh.ChangeLoginID = LogOnUser.UserID;
            wh.ChangeLoginName = LogOnUser.LoginName;
            wh.SaleAreaId = Warehouse.SaleAreaId;
            wh.ChangeDate = DateTime.Now;
            return _mservice.AddWareHouseService(wh);
        }
       
        /// <summary>
        /// 修改仓库信息
        /// Pass 1
        /// </summary>
        public int EditWareHouse(AntiFleeing_Warehouse Warehouse)
        {
            Warehouse.ChangeDate = DateTime.Now;
            Warehouse.ChangeLoginID = LogOnUser.UserID;
            Warehouse.ChangeLoginName = LogOnUser.LoginName;
            int rulset = _mservice.EditWareService(Warehouse);
            return rulset;
        }

        /// <summary>
        /// 删除
        /// Pass 1
        /// </summary>
        public int DelWare(int id)
        {
           
            return _mservice.DelWareService(id);
        }

        /// <summary>
        /// 导出EXCEL
        /// Pass 1
        /// </summary>
        public ActionResult EportExecl(string key)
        {
            var model = _mservice.GetAllWarehouse(key);
            var _byte_batch = Excel.Exprot<AntiFleeing_Warehouse>(model.ToList().Where(p => p.ViewDel == 0).ToList(),
            new string[] { "所属机构", "仓库名称", "仓库地址", "负责人", "联系电话", "备注", "操作时间" }, p =>
            {
                return new object[] { 
                            p.EnterpriseName,
                            p.WarehouseName,
                            p.Address,
                            p.Contacts,
							p.ContactTel,
							p.Remark,
							p.ChangeDate
				};
            }, "Warehouse");
            return File(_byte_batch, "application/octet-stream", string.Format("{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion
    }

}